package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.GenericComposite;
import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.QRY_Q01;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.RDT;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.alibaba.fastjson.JSON;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class HospitalBillConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgTpl("200270");
        Element requestElement = document.getRootElement();
        QBP_Q11 hl7 = (QBP_Q11) requestMessage.getHl7Message();
        GenericComposite gc = (GenericComposite) hl7.getQPD().getQpd3_UserParametersInsuccessivefields().getData();
        if (gc != null) {
            Varies varies = (Varies) gc.getComponent(1);
            if (varies != null) {
                GenericPrimitive primitive = (GenericPrimitive) varies.getData();
                String qpdString = primitive.getValue();
                String[] qpds = qpdString.split("#");
                if (qpds.length < 2) {
                    throw new RuntimeException("缺少必要参数");
                }
                for (String qpd : qpds) {
                    String[] temp = qpd.split("=");
                    if(temp.length>1){
                        requestElement.addElement(temp[0]).addText(temp[1] != null ? temp[1] : "");
                    }else {
                        requestElement.addElement(temp[0]).addText("");
                    }
                }
            }
        }
        String res = document.asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = "+ res);
        return document;
    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        logger.info("200270 message = "+ message);
        List<Map<String,Object>> resList = (List<Map<String, Object>>) JSON.parse(message);
//        List<Map<String,Object>> resList = message;

//        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);
        MSA msa = rtbK13.getMSA();
        if (resList.size()>0){
            msa.getErrorCondition().getCe1_Identifier().setValue("1");
            msa.getErrorCondition().getCe2_Text().setValue("成功");
        }else {
            msa.getErrorCondition().getCe1_Identifier().setValue("0");
            msa.getErrorCondition().getCe2_Text().setValue("无数据");
        }

        RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();
//        Element items = doc.getRootElement().element("Items");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int index = 0;
//        for (Iterator<Element> iterator = items.elementIterator(); iterator.hasNext(); ) {
//            Element el = iterator.next();
        for (int i = 0;i<resList.size();i++){
            RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
            CE ce = new CE(rtbK13);
            ce.getCe1_Identifier().setValue("RD");
            StringBuffer buffer = new StringBuffer();
//            String time = String.valueOf(resList.get(i).get("time"));
            Long time = new Long(String.valueOf(resList.get(i).get("time")));
            String itemName = String.valueOf(resList.get(i).get("itemName")).replace("#","&copy");
            buffer.append("itemId=").append(resList.get(i).get("itemId")).append("#")
                    .append("itemName=").append(itemName).append("#")
                    .append("itemType=").append(resList.get(i).get("itemType")).append("#")
                    .append("sizes=").append(resList.get(i).get("sizes")).append("#")
                    .append("unit=").append(resList.get(i).get("unit")).append("#")
                    .append("price=").append(resList.get(i).get("price")).append("#")
                    .append("num=").append(resList.get(i).get("num")).append("#")
                    .append("money=").append(resList.get(i).get("money")).append("#")
                    .append("time=").append(sdf.format(time)).append("#")
                    .append("moneyType=").append(resList.get(i).get("moneyType")).append("#")
                    .append("ext=").append(resList.get(i).get("ext"));

            ce.getCe2_Text().setValue(buffer.toString());
            rdt.getColumnValue().setData(ce);
            definition.insertRDT(rdt, index++);
        }
        return rtbK13;
    }



    @Override
    public Message generatorReqMessage() throws Exception {
        QRY_Q01 qryQ01 = new QRY_Q01();
        qryQ01.initQuickstart("QRY_Q01", "QRY_Q01", "A");
        
        return null;
    }
}
